package com.test.CronController;

import com.test.controller.MyController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Lazy(value=false)   //立即加载
@Component
@EnableScheduling
@Controller
public class DynamicCronTask implements SchedulingConfigurer {

    /*如何通过前端动态修改 定时任务的周期 */


    //springboot自带日志 slf4j+logback
    Logger logger= LoggerFactory.getLogger(MyController.class);


    public static String cron = "0/4 * * * * ?";


    //前端发送请求通过修改  cron  重置定时任务周期
    @RequestMapping("/setDynamicCronTask")
    @ResponseBody
    public void setSpringDynamicCronTask(HttpServletRequest request, String setCron) {
        System.out.println("cron setDynamicCronTaskto:" + setCron);

        setCron="0/8 * * * * ?";

        cron = setCron;
        System.err.println("cron change to:" + cron);

    }


    //项目启动时此方法会被自动调用
    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegister) {
        taskRegister.addTriggerTask(new Runnable() {
            @Override
            public void run() {
                // 逻辑任务 定时执行
                System.out.println("dynamicCronTask is running...");
            }
        }, new Trigger() {
            @Override
            public Date nextExecutionTime(TriggerContext triggerContext) {
                // 任务触发，可修改任务的执行周期
                CronTrigger trigger = new CronTrigger(cron);
                System.out.println("cron:" + cron);
                Date nextExecutor = trigger.nextExecutionTime(triggerContext);
                return nextExecutor;
            }
        });
    }


}